#include "parser.h"
#include "Debug.h"
#include <iostream>

Parser::Parser(char delimiter)
{
	this->setDelemiter(delimiter);
}

string Parser::getField(string &str,int fieldnum)
{
	int pos;
	string pstr_a = str;
	string gstr;
	char buf[100];

	bzero(buf, 100);	

	if(fieldnum > this->numField(str))
	{
		Debug("getField overflow\n");
		return "";
	}	

	for (int i = 0; i <= fieldnum; i++)
	{
		if((pos = pstr_a.find(this->getDelimiter())) == -1)
			pos = pstr_a.length();
		strncpy(buf, pstr_a.data(), pos);
		pstr_a.erase(0, pos + 1);
		buf[pos] = 0;
	}
	
	gstr = buf;

	return gstr;
}

bool Parser::addField(string &str, string &sstr, int fieldnum)
{
	int pos;

	if(fieldnum > (this->numField(str) + 1))
	{
		Debug("add Field overflow\n");
		return false;
	}			
	

	if(fieldnum == 0)
	{
		str.insert(0, sstr);
		str.insert(sstr.length(),this->turnToStr(this->getDelimiter()));
		return true;
	}
	if(fieldnum < this->numField(str))
	{
		pos = this->findnum(str, this->getDelimiter(), fieldnum) + 1;
		cout << "pos: " << pos << endl;
		str.insert(pos, sstr);
		Debug("insert sstr\n");
		str.insert(pos + sstr.length(), this->turnToStr(this->getDelimiter()));
		Debug("insert delimiter\n");
	} else {
		Debug("At the end insert delimiter\n");
		str.insert(str.length(), this->turnToStr(this->getDelimiter()));
		str.insert(str.length(), sstr);
	}

	return true;
}

bool Parser::deleteField(string &str, int fieldnum)
{
	if(fieldnum > this->numField(str))
	{
		Debug("add Field overflow\n");
		return false;
	}

	string sstr;
	sstr = this->getField(str,fieldnum);

	if (fieldnum == 0){
		str.erase(0,sstr.length() + 1);
	}
	else{
		int pos = this->findnum(str,this->getDelimiter(),fieldnum);
		str.erase(pos,sstr.length() + 1);
	}

	return true;
}

int Parser::numField(string &str)
{
	return count(str.begin(), str.end(), this->getDelimiter()) + 1;
}

/**/
int Parser::findnum(string &str, char delimiter , int num)
{
	int n = 0;
	
	if(num == 0)
		return 0;
	
	for(int i = 0; i < (int)str.length(); i++)
	{
		if(str[i] == delimiter|| i == (int)(str.length() - 1)) n++;
		if(n == num) return i;
	}
	return -1;
}

void Parser::setDelemiter(char delimiter)
{
	this->delimiter = delimiter;
}

char Parser::getDelimiter()const
{
	return this->delimiter;
}

string Parser::turnToStr(const char ch)
{
	string str;
	str = ch;
	return str;
}



